package com.kb.medical.service.impl;


import com.kb.medical.entity.PdfTxt;
import com.kb.medical.entity.UserFile;
import com.kb.medical.mapper.mp.PdfTxtMapper;
import com.kb.medical.service.PdfTxtService;
import com.kb.medical.service.ex.InsertException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

import static com.kb.medical.util.Text_Pdf.getNumberFromString;
import static com.kb.medical.util.Text_Pdf.readFileContent;


@Service//@Service注解：将当前类的对象交给Spring来管理，自动创建对象
public class PdfTxtServiceImpl implements PdfTxtService {
    @Resource
    private PdfTxtMapper pdfTxtMapper;


    @Override
    public void pdfTxtInsert(PdfTxt pdfTxt) {
        Integer rows = pdfTxtMapper.PdfTextInsert(pdfTxt);
        if (rows != 1) {
            throw new InsertException("在插入数据过程中产生了未知异常");
        }
    }

    @Override
    public PdfTxt TxtFindByDocumentId(int documentId) {
        PdfTxt result = pdfTxtMapper.TxtFindByDocumentId(documentId);
        return result;
    }

    @Override
    public String ReadFile(UserFile userFile, String path) {
        File folder = new File(path);
        File[] files = folder.listFiles(); // 获取文件夹中的所有文件
        for (File file : files) {
            if (file.isFile()) { // 判断是否是文件
                String fileName = file.getName();
                String fileContent = readFileContent(file);
                Integer number = getNumberFromString(fileName);
                System.out.println(fileName + " : " + fileContent);
                PdfTxt pdfTxt = new PdfTxt();
                pdfTxt.setDocumentId(userFile.getId());
                pdfTxt.setPage(number);
                pdfTxt.setLike(0);
                pdfTxt.setClick(0);
                pdfTxt.setPdfText(fileContent);
                pdfTxt.setUserid(userFile.getUserid());
                pdfTxt.setFilename(userFile.getFileName());
                pdfTxt.setUploadUserName(userFile.getUploadUserName());
                pdfTxt.setUploadTime(new Date());
                String localPath = userFile.getPdfPath();
                pdfTxt.setPath(localPath);


                pdfTxtInsert(pdfTxt);

            }
        }
        String result = "pdf文本写入成功";
        return result;
    }
}
